package org.agora.photogallery.client.presenter;

import java.util.ArrayList;

import org.agora.photogallery.client.event.GalleryClickedEvent;
import org.agora.photogallery.client.event.ShowGalleryEvent;
import org.agora.photogallery.client.event.ShowGalleryEventHandler;
import org.agora.photogallery.client.model.Gallery;
import org.agora.photogallery.client.service.PhotoService;
import org.agora.photogallery.client.view.GalleryView;



import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.inject.Inject;

public class GalleryPresenter implements Presenter, GalleryView.GalleryPresenter, ValueChangeHandler<String>, ShowGalleryEventHandler{
	private static boolean isBind = false;
	private final GalleryView galleryView; 
	private final PhotoService photoService;
	private final HandlerManager eventBus;
	
	@Inject
	public GalleryPresenter(GalleryView view, PhotoService photoService, HandlerManager  hm){
		this.galleryView = view;
		this.photoService = photoService;
		eventBus = hm;
		eventBus.addHandler(ShowGalleryEvent.TYPE, this);
	}
	
	@Override
	public void present(HasWidgets container){
		
		galleryView.setPresenter(this);
		container.add(galleryView.asWidget());
	}
	private void bind(){
		if(!isBind){
		photoService.getGalleries(
				new AsyncCallback<ArrayList<Gallery>>(){

					@Override
					public void onFailure(Throwable caught) {
						GWT.log("Could not connect to Picasa");						
					}

					@Override
					public void onSuccess(ArrayList<Gallery> result) {
						setGalleries(result);
						isBind = true;
						galleryView.show();
					}
				}					
		);
	
		} else {
			galleryView.show();
		}

	}
	public final void setGalleries(ArrayList<Gallery> galleires){
		galleryView.setData(galleires);
	}

	@Override
	public void onItemClicked(Gallery g) {
		GalleryClickedEvent event = new GalleryClickedEvent(g);
		History.newItem("gallery=" +g.getId());
		 galleryView.hide();
		eventBus.fireEvent(event);
		
	}
	@Override
	public void onValueChange(ValueChangeEvent<String> event) {
//		if (event.getValue().equals(anObject))
		
	}
	@Override
	public void OnShowEvent(ShowGalleryEvent event) {
		bind();
		
	}
	
	

}
